from channels.generic.websocket import AsyncWebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync

# 假设这是您的消息历史记录，实际应用中应使用数据库或其他持久化存储
history_messages = []

class ChatConsumer(AsyncWebsocketConsumer):
    async def websocket_connect(self, message):
        print('客户端来握手')
        await self.accept()
        await self.send("你好，客户端")

        # 获取群号
        group = self.scope['url_route']['kwargs'].get("group")
        # 将这个客户端连接对象加入到群组
        await self.channel_layer.group_add(group, self.channel_name)

        # 发送历史消息给新成员
        for history_message in history_messages:
            await self.send(text_data=history_message)

    async def websocket_receive(self, message):
        # 获取群号
        group = self.scope['url_route']['kwargs'].get("group")
        # 发送消息到群组
        await self.channel_layer.group_send(group, {"type": "xx_oo", "message": message})

        # 存储消息到历史记录
        history_messages.append(message["text"])

    async def xx_oo(self, event):
        text = event["message"]["text"]
        await self.send(text_data=text)

    async def self_stop_conn(self, text_msg):
        if text_msg == "close":
            await self.close()
            raise StopConsumer()

    async def websocket_disconnect(self, message):
        print("断开连接")
        group = self.scope['url_route']['kwargs'].get("group")
        # 客户端与服务器断开连接时自动触发
        await self.channel_layer.group_discard(group, self.channel_name)
        raise StopConsumer()
